import React from 'react'
import Paper from 'material-ui/Paper'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router-dom'
import { withStyles } from 'material-ui/styles'
import AccountCircle from 'material-ui-icons/AccountCircle'
import Button from 'material-ui/Button'
import Helmet from 'react-helmet'

import TextField from 'material-ui/TextField'
import { inject, observer } from 'mobx-react'
import UserStore from '../../stores/user_store'
import style from './styles'

@inject((stores) => {
  const store = {
    user: stores.user,
  }
  return store
})
@observer
class Login extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      accessToken: '',
    }
    this.handleTextFieldChange = this.handleTextFieldChange.bind(this)
    this.doLogin = this.doLogin.bind(this)
  }
  componentDidMount() {

  }
  doLogin() {
    const { accessToken } = this.state
    const { user } = this.props
    const { redirect } = this.props.match.params
    user.login(accessToken).then((res) => {
      if (res && res.id) {
        this.props.history.push(decodeURIComponent(redirect))
      }
    })
  }
  handleTextFieldChange(e) {
    this.setState({
      accessToken: e.target.value,
    })
  }
  render() {
    const { classes } = this.props
    return (
      <div className={classes.container}>
        <Helmet>
          <title>登录-CNode中文社区</title>
        </Helmet>
        <Paper className={classes.paper}>
          <div className={classes.top}>
            <div className={classes.bg} />
            <div className={classes.avatar}>
              <AccountCircle className={classes.account} />
            </div>
            <div className={classes.tip}>未登录</div>
          </div>
          <div className={classes.token}>
            <TextField
              className={classes.textField}
              placeholder="请输入请输入Cnode AccessToken"
              label="请输入请输入Cnode AccessToken"
              helperText={this.state.helperText}
              onChange={this.handleTextFieldChange}
              labelClassName={classes.textLabel}
              inputProps={{
                className: classes.input,
              }}
            />
          </div>
          <Button
            className={classes.loginBtn}
            color="primary"
            raised
            onClick={this.doLogin}
          >
            登录
          </Button>
        </Paper>
      </div>
    )
  }
}
export default withRouter(withStyles(style)(Login))
Login.propTypes = {
  classes: PropTypes.objectOf(Object),
  user: PropTypes.instanceOf(UserStore),
  history: PropTypes.objectOf(Object),
  match: PropTypes.objectOf(Object),
}
